﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CIT.WMS.houseWork.Helper;

namespace CIT.WMS.Move
{
    public partial class FrmPrepareMaterial : Form
    {
        bool flag = false;
        bool result = false;
        bool check_doc = false;
        public FrmPrepareMaterial()
        {
            InitializeComponent();
            databind();
        }

        private void databind()
        {
            string strSql = string.Format(@"SELECT A.S_Doc_NO FROM dbo.T_Bllb_StorageDoc_tbsd A 
LEFT JOIN dbo.T_Bllb_DocType_tbdt B ON A.S_Doc_Type=B.TYPE_CODE 
WHERE B.Prepare_Flag='Y' AND A.Close_Flag='N' ORDER BY a.Create_Time desc");
            DataTable dt_doc = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
            DataRow dr = dt_doc.NewRow();
            dr["S_Doc_NO"] = string.Empty;
            dr["S_Doc_NO"] = string.Empty;
            dt_doc.Rows.InsertAt(dr, 0);
            cbo_PO.DisplayMember = "S_Doc_NO";
            cbo_PO.ValueMember = "S_Doc_NO";
            cbo_PO.DataSource = dt_doc;
         
        }

        private void txt_reelid_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (txt_reelid.Text.Trim() == string.Empty)
                {
                    lbl_msg.Text = "物料条码不能为空.";
                    lbl_msg.ForeColor = Color.Red;
                    txt_reelid.Text = string.Empty; ;
                    txt_reelid.Focus();
                    return;
                }
                ClearControl();
                if (!CheckDoc())//校验备料单
                {           
                    return;
                }
             
                //校验物料SN是否在库并且可用
                string strSql = string.Format(@"SELECT Lock_Flag,Enable,MaterialCode,QTY,Storage_SN,DateCode FROM dbo.T_Bllb_StockInfo_tbsi WHERE SerialNumber ='{0}'", txt_reelid.Text.Trim());
                DataTable dt_material = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_material.Rows.Count == 0)
                {
                    lbl_msg.Text = "物料条码不存在.";
                    lbl_msg.ForeColor = Color.Red;
                    txt_reelid.Text = string.Empty; ;
                    txt_reelid.Focus();
                    return;
                }
                string lock_flag=dt_material.Rows[0]["Lock_Flag"].ToString() ;//状态
                string error_text = string.Empty;
                switch (lock_flag)
                { 
                    case "1":
                        error_text = "物料盘点中";
                        break;
                    case "2":
                        error_text = "物料冻结中";
                        break;
                    case "3":
                        error_text = "物料二次送检中";
                        break;
                    case "4":
                        error_text = "物料被报废";
                        break;
                    case "5":
                        error_text = "物料二检NG";
                        break;
                    case "6":
                        error_text = "物料备料中";
                        break;
                    case "7":
                        error_text = "物料已出库";
                        break;
                    case "8":
                        error_text = "物料被合盘";
                        break;
                    case "9":
                        error_text = "物料已出库，并冻结中";
                        break;
                }
                if (error_text != string.Empty)
                {
                    lbl_msg.Text = error_text;
                    lbl_msg.ForeColor = Color.Red;
                    txt_reelid.Text = string.Empty; ;
                    txt_reelid.Focus();
                    return;
                }
        
                string doc_no = cbo_PO.SelectedValue.ToString();//备料单
                string MaterialCode = dt_material.Rows[0]["MaterialCode"].ToString();//料号
                int qty = SqlInput.ChangeNullToInt(dt_material.Rows[0]["QTY"], 0);//数量

                //判断物料是否存在备料单中
                strSql = string.Format(@"SELECT Plan_Qty,QTY FROM dbo.T_Bllb_StorageDocMaterial_tsdm WHERE S_Doc_NO='{0}' AND MaterialCode='{1}'", doc_no, MaterialCode);

                DataTable dt_docMaterial = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_docMaterial.Rows.Count == 0)
                {
                    lbl_msg.Text = "备料单中不存在物料" + dt_material.Rows[0]["MaterialCode"].ToString();
                    lbl_msg.ForeColor = Color.Red;
                    txt_reelid.Text = string.Empty; ;
                    txt_reelid.Focus();
                    return;
                }
                else if (SqlInput.ChangeNullToInt(dt_docMaterial.Rows[0]["Plan_Qty"], 0) < SqlInput.ChangeNullToInt(dt_docMaterial.Rows[0]["QTY"], 0)+qty)//备料数量是否已达到
                {
                    lbl_msg.Text = "备料单中物料" + dt_material.Rows[0]["MaterialCode"].ToString() + "将会超过计划数" + SqlInput.ChangeNullToInt(dt_docMaterial.Rows[0]["Plan_Qty"], 0);
                    lbl_msg.ForeColor = Color.Red;
                    txt_reelid.Text = string.Empty; ;
                    txt_reelid.Focus();
                    return;
                }
                strSql = string.Format(@"SELECT Source_Storage FROM dbo.T_Bllb_StorageDoc_tbsd WHERE S_Doc_NO='{0}'",doc_no);
                DataTable dt_docStorage = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_docStorage.Rows.Count > 0)
                {
                    string storagesn = SqlInput.ChangeNullToString(dt_docStorage.Rows[0]["Source_Storage"]);
                    if (storagesn != string.Empty & storagesn != SqlInput.ChangeNullToString(dt_material.Rows[0]["Storage_SN"]))
                    {
                        lbl_msg.Text = "备料单只能备仓库"+storagesn+"中的物料";
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                    if (storagesn == string.Empty)
                    {
                        strSql = string.Format(@"SELECT TOP 1 DateCode FROM dbo.T_Bllb_StockInfo_tbsi WHERE MaterialCode ='{0}' and Lock_Flag='0' ORDER BY DateCode ASC", MaterialCode);
                    }
                    else
                    {
                        strSql = string.Format(@"SELECT TOP 1 DateCode FROM dbo.T_Bllb_StockInfo_tbsi WHERE MaterialCode ='{0}' and Storage_SN='{1}' and Lock_Flag='0' ORDER BY DateCode ASC", MaterialCode, storagesn);
                    }
                    DataTable dt_datecode = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    if (dt_datecode.Rows.Count > 0)
                    {
                        string datecode = SqlInput.ChangeNullToString(dt_datecode.Rows[0]["DateCode"]);
                        if (SqlInput.ChangeNullToString(dt_material.Rows[0]["DateCode"]) != datecode)
                        {
                            lbl_msg.Text = "请选择DateCode为" + datecode + "物料";
                            lbl_msg.ForeColor = Color.Red;
                            txt_reelid.Text = string.Empty; ;
                            txt_reelid.Focus();
                            return;
                        }
                    }
                    else
                    {
                        lbl_msg.Text = "仓库" + storagesn + "中没有此种物料";
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }

                }
                else
                {
                    lbl_msg.Text = "备料单不存在";
                    lbl_msg.ForeColor = Color.Red;
                    txt_reelid.Text = string.Empty; ;
                    txt_reelid.Focus();
                    return;
                }


                strSql = string.Format(@"UPDATE T_Bllb_StorageDocMaterial_tsdm SET QTY=QTY+{2} WHERE S_Doc_NO='{0}' AND MaterialCode='{1}'", doc_no, MaterialCode,qty);

                Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                strSql = string.Format(@"INSERT INTO dbo.T_Bllb_StorageDocDetail_tbsdd
                                                ( S_Doc_NO ,
                                                  MaterialCode ,
                                                  QTY ,
                                                  Create_Time ,
                                                  Creator ,
                                                  SerialNumber 
                                                )
                                        VALUES  ( '{0}' , -- S_Doc_NO - nvarchar(50)
                                                  '{1}' , -- MaterialCode - nvarchar(50)
                                                  {2} , -- QTY - int
                                                  GETDATE() , -- Create_Time - datetime
                                                  '{3}' , -- Creator - nvarchar(50)
                                                  '{4}'  -- SerialNumber - nvarchar(50)   
                                                 
                                                )", doc_no, MaterialCode, qty, Utils.uContext.UserIDk__BackingField, txt_reelid.Text.Trim());
                Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);

                strSql = string.Format(@"UPDATE dbo.T_Bllb_StockInfo_tbsi SET Lock_Flag='6' WHERE SerialNumber='{0}'", txt_reelid.Text.Trim());
                Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                lbl_msg.Text = "备料成功";
                lbl_msg.ForeColor = Color.Green;
                lbl_PO.Text = doc_no;
                lbl_QTY.Text = qty.ToString();
                lbl_TotalQty.Text = (qty + SqlInput.ChangeNullToInt(dt_docMaterial.Rows[0]["QTY"], 0)).ToString();
                lbl_MaterialCode.Text = MaterialCode;
                txt_reelid.Text = string.Empty; ;
                txt_reelid.Focus();
            }
        }

        private void cbo_PO_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearControl();
        }

        private void ClearControl()
        {
            lbl_MaterialCode.Text = string.Empty;
            lbl_PO.Text = string.Empty;
            lbl_QTY.Text = string.Empty;
            lbl_TotalQty.Text = string.Empty;
            lbl_msg.Text = string.Empty;
        }

        private void cbo_PO_LostFocus(object sender, EventArgs e)
        {
            if (CheckDoc())
            {
                lbl_msg.Text = "备料单设置OK";
                lbl_msg.ForeColor = Color.Green;
                return;
            }
        
        }
        /// <summary>
        /// 校验备料单
        /// </summary>
        /// <returns></returns>
        private bool CheckDoc()
        {
            if (cbo_PO.SelectedValue.ToString() == string.Empty)
            {
                lbl_msg.Text = "备料单不能为空";
                lbl_msg.ForeColor = Color.Red;
                return false;
            }
            string strSql = string.Format(@"SELECT A.Close_Flag,B.Prepare_Flag FROM dbo.T_Bllb_StorageDoc_tbsd A 
LEFT JOIN dbo.T_Bllb_DocType_tbdt B ON A.S_Doc_Type=B.TYPE_CODE WHERE  A.S_Doc_NO= '{0}'", cbo_PO.Text.Trim());
            DataTable dt_po = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
            if (dt_po.Rows.Count == 0)
            {
                lbl_msg.Text = "备料单不存在";
                lbl_msg.ForeColor = Color.Red;
                return false;
            }
            else if (SqlInput.ChangeNullToString(dt_po.Rows[0]["Close_Flag"]) == "Y")
            {
                lbl_msg.Text = "备料单已关闭，重新加载备料单";
                lbl_msg.ForeColor = Color.Red;
                databind();
                return false;
            }
            else if (SqlInput.ChangeNullToString(dt_po.Rows[0]["Prepare_Flag"]) != "Y")
            {
                lbl_msg.Text = "备料单有误，请重新选择";
                lbl_msg.ForeColor = Color.Red;
                return false;
            }
            return true;
        }
    }
}